import { glob } from 'glob'
import path from 'path'
import fsPromises from 'fs/promises'
import config, { saveConfig } from '../config/index.js'
import dbWeb from '../lib/doubao/doubao-web.js'
import { pdfToReportPrompt, pdfToReportPrompt251110 } from '../lib/llm/prompt.js'

import { sleep } from '../util.js'

class API {
  async uplpad() {
    // const data = config.papers
    const data = config.papersPending
    let files = await glob(data.src)

    if (data.end == 0) data.end = files.length

    for (let i = data.start; i < data.end; i++) {
      await this.task(data, files, i)
    }
  }

  async task(config, files, index, frequency = 1) {
    if (frequency >= 4) return console.log('跳过，不再重试')

    // 进度
    console.log(`${index}/${config.end}`, ((index / config.end) * 100).toFixed(2))

    config.start = index
    saveConfig()

    const srcPath = files[index]

    const chatResult = await dbWeb.upload(srcPath, pdfToReportPrompt251110)

    const distPath = path.join(config.dist, path.parse(srcPath).name)

    let json
    try {
      json = extractJsons(chatResult)
    } catch (e) {
      console.error('提取json失败', e)
      fsPromises.writeFile(distPath + '-error-提取JSON失败.txt', chatResult)
      return
    }

    console.log('json', json)

    try {
      fsPromises.writeFile(distPath + '.json', JSON.stringify(json.extract))
    } catch (error) {
      console.error('json parse error，直接保存', e)
      fsPromises.writeFile(distPath + '-error-保存JSON失败.txt', chatResult)
    }

    await sleep(5 * 1000)
    // if (json.score >= 80) {
    //   try {
    //     fsPromises.writeFile(distPath + '.json', JSON.stringify(json.extract))
    //   } catch (error) {
    //     console.error('json parse error，直接保存', e)
    //     fsPromises.writeFile(distPath + '-error-保存JSON失败.txt', chatResult)
    //   }

    //   await sleep(30 * 1000)
    // }
    // // 低于80重试
    // else {
    //   await sleep(30 * 1000)
    //   await this.task(config, files, index, frequency + 1)
    // }
  }
}

function extractJsons(str) {
  // 1. 过滤掉 {insert_element_X_} 占位符
  str = str.replace(/\{insert\\_element\\_\d+\\_\}/g, '')

  // 尝试修复非法转义
  str = str.replace(/\\_/g, '_')
  str = str.replace(/\\N/g, '\\\\N')

  // 查找所有可能包含JSON的部分
  const jsonRegex = /{(?:[^{}]|{(?:[^{}]|{[^{}]*})*})*}/g
  const jsonMatches = str.match(jsonRegex) || []

  // 解析两个 JSON
  let firstJson

  try {
    firstJson = JSON.parse(jsonMatches[0])
  } catch (e) {
    throw e
    // console.error('firstJson提取失败', e)
    // fsPromises.writeFile(Date.now() + '-error-firstJson提取失败.txt', str)
  }

  // let secondJson

  // try {
  //   secondJson = JSON.parse(jsonMatches[1])
  // } catch (e) {
  //   console.error('secondJson提取失败', e)
  //   fsPromises.writeFile(Date.now() + '-error-secondJson提取失败.txt', str)
  // }

  // 组合成目标对象
  return {
    extract: firstJson?.extract || firstJson, // 兼容两种格式
    // score: secondJson.score,
  }
}

// console.log(extractJsons(str));

export default new API()
